#pragma once
#include <QObject>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QPointer>
#include <QVector>

struct DailyItem {
    QString date;              // YYYY-MM-DD
    QString weekday;           // 周一..周日
    int     weatherCode = -1;  // Open-Meteo 天气码
    QString weatherText;       // 中文文案
    double  tMin = 0;          // 最低温 ℃
    double  tMax = 0;          // 最高温 ℃
    double  windSpeedMax = 0;  // 当日最大风速 m/s
    int     windDirDominant = -1;  // 当日主导风向(度)
    QString windDirText;           // 当日主导风向(中文)
};
Q_DECLARE_METATYPE(DailyItem)

struct WeatherData {
    // —— 实况
    QString city;
    double  latitude = 0;
    double  longitude = 0;
    double  temperature = 0;   // ℃
    int     humidity = -1;     // %
    double  windSpeed = 0;     // m/s
    int     weatherCode = -1;  // Open-Meteo 天气码
    int     windDirection = -1;// 0~360°
    QString windDirectionText; // 东南/北/...
    QString weekday;           // 当前周几
    QString weatherText;       // 实况中文
    QString provider = "Open-Meteo";
    QString updatedAt;         // 本地时间字符串

    // —— 预报（今天/明天/后天）
    QVector<DailyItem> daily;  // size<=3
};
Q_DECLARE_METATYPE(WeatherData)

class WeatherClient : public QObject {
    Q_OBJECT
public:
    explicit WeatherClient(QObject* parent=nullptr);
    void setTimeoutMs(int ms) { m_timeoutMs = ms; }

    // 直接经纬度抓取
    void fetchByCoordinates(double lat, double lon,
                            const QString& cityLabel=QString(),
                            const QString& lang="zh");

signals:
    void gotWeather(const WeatherData& data);
    void error(const QString& message, int httpStatus);

private:
    QNetworkAccessManager m_mgr;
    QPointer<QNetworkReply> m_replyWx;
    int m_timeoutMs = 10000;
    QString m_lang = "zh";

    QUrl    weatherUrl(double lat, double lon) const;
    void    handleWeatherFinished();
    static  QString codeToText(int code);
    static  QString degToDirZh(int deg);
    static  QString weekdayZh(const QDateTime&);
    static  QString weekdayZh(const QDate& d) { return weekdayZh(QDateTime(d.startOfDay())); }
    void    attachCommonErrorHandlers(QNetworkReply* r);
};
